﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Core.Utility.Helper
{
    /// <summary>
    /// 深度拷贝
    /// </summary>
    public class DeepCopyHelper
    {
        /// <summary>
        /// 使用JSON的方式
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        public static T Json<T>(T data) where T : class,new()
        {
            var res = JsonHelper.Deserialize<T>(JsonHelper.Serialize(data));
            return res;
        }

        /// <summary>
        /// 反射深拷贝
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static object? Reflection(object? model)
        {
            var modelType = model?.GetType();
            if (modelType?.IsValueType == true)
            {
                return model;
            }
            if (modelType?.Name == typeof(List<>).Name)
            {
                var genericType = modelType.GenericTypeArguments;
                var newObj = Activator.CreateInstance(genericType?.FirstOrDefault());
                var newList = (IList?)Activator.CreateInstance(modelType);
                foreach (var itemObj in (IList)model)
                {
                    //newList.Add(itemObj.Clone());
                    newList?.Add(Reflection(itemObj));
                }
                return newList;
            }
            if (modelType?.Name == typeof(Dictionary<,>).Name)
            {
                var genericType = modelType.GenericTypeArguments;
                var newkey = Activator.CreateInstance(genericType[0]);
                var newValue = Activator.CreateInstance(genericType[1]);
                var newDic = (IDictionary?)Activator.CreateInstance(modelType);
                var modelDic = (IDictionary)model;
                foreach (var itemkey in (modelDic.Keys))
                {
                    //newDic.Add(itemkey.Clone(), modelDic[itemkey].Clone());
                    newDic?.Add(Reflection(itemkey), Reflection(modelDic[itemkey]));
                }
                return newDic;
            }
            var pros = modelType.GetProperties();
            var newModel = Activator.CreateInstance(modelType, true);
            var newModelType = newModel?.GetType();
            var newpros = newModelType?.GetProperties();
            foreach (var pro in pros)
            {
                var newPro = newpros?.FirstOrDefault(u => u.Name == pro.Name);
                if (pro.PropertyType.IsValueType || pro.PropertyType == typeof(string))
                {
                    if (pro.GetGetMethod() != null)
                    {
                        var value = pro.GetValue(model);
                        if (pro.SetMethod != null)
                        {
                            newPro?.SetValue(newModel, value);
                        }
                    }
                }
                else
                {

                    if (pro.GetGetMethod() != null)
                    {
                        var value = pro.GetValue(model);
                        if (newPro?.SetMethod != null)
                        {
                            newPro.SetValue(newModel, Reflection(value));
                        }
                    }
                }
            }
            return newModel;
        }

        /// <summary>
        /// 泛型反射深拷贝
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="inM"></param>
        /// <returns></returns>
        public static T? ReflectionT<T>(T inM)
        {
            Type? t = inM?.GetType();
            T? outM = (T?)Reflection(inM);
            return outM;
        }
    }

    /// <summary>
    /// 深拷贝，使用表达式树  
    /// <code>
    /// UserInfo newInfo = DeepCopyByTransExpression&lt;UserInfo, UserInfo&gt;.Trans(info);
    /// </code>
    /// </summary>
    /// <typeparam name="TIn"></typeparam>
    /// <typeparam name="TOut"></typeparam>
    public static class DeepCopyByTransExpression<TIn, TOut>
    {
        private static readonly Func<TIn, TOut> cache = GetFunc();
        private static Func<TIn, TOut> GetFunc()
        {
            ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p");
            List<MemberBinding> memberBindingList = new List<MemberBinding>();

            foreach (var item in typeof(TOut).GetProperties())
            {
                if (!item.CanWrite) continue;
                MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name));
                MemberBinding memberBinding = Expression.Bind(item, property);
                memberBindingList.Add(memberBinding);
            }

            MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray());
            Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[] { parameterExpression });

            return lambda.Compile();
        }

        /// <summary>
        /// 深拷贝
        /// </summary>
        /// <param name="tIn"></param>
        /// <returns></returns>
        public static TOut Trans(TIn tIn)
        {
            return cache(tIn);
        }
    }
}
